home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2007 December / PCWKCD1207B.iso / Blogowanie poza sfera / Flock 1.0 beta / flock-1.0RC3.en-US.win32.exe / flock / components / flockSearchAPIAmazon.js < prev    next >
Text File  |  2007-10-18  |  12KB  |  286 lines

  1. //
  2. // BEGIN FLOCK GPL
  3. // 
  4. // Copyright Flock Inc. 2005-2007
  5. // http://flock.com
  6. // 
  7. // This file may be used under the terms of of the
  8. // GNU General Public License Version 2 or later (the "GPL"),
  9. // http://www.gnu.org/licenses/gpl.html
  10. // 
  11. // Software distributed under the License is distributed on an "AS IS" basis,
  12. // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  13. // for the specific language governing rights and limitations under the
  14. // License.
  15. // 
  16. // END FLOCK GPL
  17. //
  18.  
  19. const AMAZON_SEARCH_CID         = Components.ID('{c3cc0113-4df3-4b49-ae86-b9014776dee6}');
  20.  
  21. const nsISupports                   = Components.interfaces.nsISupports;
  22. const nsIClassInfo                  = Components.interfaces.nsIClassInfo;
  23. const nsIFactory                    = Components.interfaces.nsIFactory;
  24. const nsIProperties                 = Components.interfaces.nsIProperties;
  25. const nsILocalFile                  = Components.interfaces.nsILocalFile;
  26. const nsIFile                       = Components.interfaces.nsIFile;
  27. const nsIIOService                  = Components.interfaces.nsIIOService;
  28. const nsIFileProtocolHandler        = Components.interfaces.nsIFileProtocolHandler;
  29. const nsIRDFRemoteDataSource        = Components.interfaces.nsIRDFRemoteDataSource;
  30. const nsIRDFDataSource              = Components.interfaces.nsIRDFDataSource;
  31. const flockISearchService           = Components.interfaces.flockISearchService;
  32. const nsIXMLHttpRequest             = Components.interfaces.nsIXMLHttpRequest;
  33.  
  34. const AMAZON_SEARCH_CONTRACTID       = '@flock.com/?flock-search-amazon;1';
  35. const DIRECTORY_SERVICE_CONTRACTID  = '@mozilla.org/file/directory_service;1';
  36. const LOCAL_FILE_CONTRACTID         = '@mozilla.org/file/local;1';
  37. const PREFERENCES_CONTRACTID        = '@mozilla.org/preferences-service;1';
  38. const IO_SERVICE_CONTRACTID         = '@mozilla.org/network/io-service;1';
  39. const XMLHTTPREQUEST_CONTRACTID     = '@mozilla.org/xmlextras/xmlhttprequest;1'
  40.  
  41. const flockIError = Components.interfaces.flockIError;
  42. const FLOCK_ERROR_CONTRACTID = '@flock.com/error;1'
  43.  
  44. const AMAZON_SEARCH_API_URL = "http://xml.amazon.com/onca/xml3";
  45. const AMAZON_DEVELOPER_TOKEN = "0XYJJ825QSB9Q7F2XN02";
  46. const AMAZON_ASSOCIATES_ID = "flockcom-20";
  47.  
  48.  
  49. function amazonSearchService() {
  50.   var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService);
  51.   var bundle = sbs.createBundle("chrome://flock/locale/search/search.properties");
  52.   this.serviceName = bundle.GetStringFromName("flock.search.api.amazon");
  53. }
  54.  
  55. amazonSearchService.prototype.shortName = "amazon";
  56. amazonSearchService.prototype.icon = "chrome://browser/skin/flock/search/amazon.ico";
  57. amazonSearchService.prototype.ref = "urn:flock:search:amazon";
  58. amazonSearchService.prototype.fullResultsUrl = "http://amazon.com/s/ref=nb_ss_gw/102-3108539-8940162?url=search-alias%3Daps&Go.x=0&Go.y=0&Go=Go&field-keywords=";
  59.  
  60. amazonSearchService.prototype.search = function (aQuery, aNumResults, aListener, aDatasource) {
  61.     var inst = this;
  62.     
  63.     if (!aQuery.length) return;
  64.     // eg. http://xml.amazon.com/onca/xml3?t=[Associates ID goes here]&dev-t=[Developer Token goes here]&KeywordSearch=dogs&mode=books&type=lite&page=1&f=xml
  65.     var escapedQuery = encodeURIComponent(aQuery);
  66.     var url = AMAZON_SEARCH_API_URL + "?" 
  67.        + "t=" + AMAZON_ASSOCIATES_ID
  68.        + "&dev-t=" + AMAZON_DEVELOPER_TOKEN
  69.        + "&BlendedSearch=" + escapedQuery
  70.        + "&Keywords=" + escapedQuery
  71.        + "&type=lite"
  72.        + "&f=xml"
  73.        + "&page=1";
  74.  
  75.     debug(url + " < call\n");
  76.     this.req = Components.classes[XMLHTTPREQUEST_CONTRACTID].createInstance(nsIXMLHttpRequest);
  77.     this.req instanceof Components.interfaces.nsIJSXMLHttpRequest;
  78.     this.req.open('GET', url, true);
  79.     var req = this.req;    
  80.     //debug('request is ' + req + '\n');
  81.     this.req.onreadystatechange = function (aEvt) {
  82.       if(inst.req.readyState == 4) {
  83.           // debug("\nRESPONSE\n" + inst.xmlhttp.responseText);
  84.           try {
  85.               if(req.status == 200 || req.status == 201) {
  86.                  try {
  87.                      //processor(listener, inst);
  88.                     debug(req.responseText);
  89.                      var rdf = inst.readXML(req.responseXML, aNumResults, aDatasource);
  90.                      var numResults = inst.getNumResults(req.responseXML);
  91.                      aListener.foundResults(numResults, rdf, inst.shortName, aQuery);
  92.                  } catch(e) {
  93.                      debug(e + " " + e.lineNumber+"\n");
  94.                  }
  95.               }
  96.               else {
  97.                   var faultString = req.responseText;
  98.                   // listener.onFault(faultString);
  99.               }
  100.           } catch(e) {
  101.               debug(e + " " + e.fileName + " " + e.lineNumber + "\n");
  102.               //listener.onError(inst.ERROR_PARSER);
  103.           }
  104.       }
  105.     }
  106.     
  107.     this.req.send(null);  
  108. }
  109.  
  110. amazonSearchService.prototype.getNumResults = function (xmlDoc) {
  111.     return 10;
  112.     try {
  113.         var results = xmlDoc.getElementsByTagName("item"); 
  114.         return results.length;
  115.     } catch (ex) {
  116.     
  117.     }
  118. }
  119.  
  120. amazonSearchService.prototype.readXML = function (xmlDoc, aNumResults, aDatasource) {
  121.   try {
  122.     var resultSet = xmlDoc.getElementsByTagName("ProductInfo")[0];                                                              
  123.     //var totalResultsAvailable = parseInt(xmlDoc.getElementsByTagName("querycount")[0].firstChild.nodeValue);
  124.     //var totalResultsReturned = parseInt(xmlDoc.getElementsByTagName("item").length);                                      
  125.     //var firstResultPosition = parseInt(resultSet.getAttribute("firstResultPosition"));                                        
  126.     //var start = firstResultPosition;                                                                                          
  127.     //var end = firstResultPosition + totalResultsReturned - 1;                                                                 
  128.     var results = xmlDoc.getElementsByTagName("Details"); 
  129.  
  130.     // Create an in-memory datasource
  131.     var rdfService = Components.classes["@mozilla.org/rdf/rdf-service;1"]
  132.         .getService(Components.interfaces.nsIRDFService);
  133.     var rdfContainerUtils = Components.classes["@mozilla.org/rdf/container-utils;1"]
  134.         .getService(Components.interfaces.nsIRDFContainerUtils);
  135.     // Fill it with the results
  136.     var rootContainer = rdfContainerUtils.MakeSeq(aDatasource, rdfService.GetResource("urn:flock:search:amazon"));
  137.  
  138.     var categories = xmlDoc.getElementsByTagName('ProductLine');
  139.     for (var i=0; i < categories.length; i++) {
  140.         // let's create the type container
  141.         var type = categories[i].getElementsByTagName('Mode')[0].firstChild.nodeValue;
  142.         //debug(' >>> amazon type is ' + type + '\n');
  143.         var typeNode = rdfService.GetResource("http://flock.com/rdf#type-" + type);
  144.         var typeContainer = rdfContainerUtils.MakeSeq(aDatasource, typeNode);
  145.         
  146.         // .. and give this category a name
  147.         aDatasource.Assert(typeNode, rdfService.GetResource("http://home.netscape.com/NC-rdf#Name"), rdfService.GetLiteral(type), true);
  148.         // make this of type "category
  149.         aDatasource.Assert(typeNode, rdfService.GetResource("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), rdfService.GetResource("http://flock.com/rdf#category"), true);
  150.         
  151.         
  152.         var relevanceRank = parseInt(categories[i].getElementsByTagName('RelevanceRank')[0].firstChild.nodeValue);        
  153.         if (relevanceRank > 2) continue;
  154.         debug('the relevance rank is ' + relevanceRank + '\n\n\n');
  155.         
  156.         
  157.         var results = categories[i].getElementsByTagName('Details');
  158.         
  159.         // append the items to the category
  160.         for (var j=0; j < results.length; j++) {
  161.             var result = results[j];                                                                                                
  162.             var title = result.getElementsByTagName('ProductName')[0].firstChild.nodeValue;
  163.             var clickUrl = result.getAttribute('url');
  164.             var url = clickUrl;
  165.             var thumbnailUrl = result.getElementsByTagName('ImageUrlSmall')[0].firstChild.nodeValue;
  166.             
  167.             var listPrice = result.getElementsByTagName('ListPrice');
  168.             if (listPrice.length) listPrice = listPrice[0].firstChild.nodeValue;
  169.             
  170.             var amazonPrice = result.getElementsByTagName('OurPrice');
  171.             if (amazonPrice.length) amazonPrice = amazonPrice[0].firstChild.nodeValue;
  172.             
  173.             var usedPrice = result.getElementsByTagName('UsedPrice');
  174.             if (usedPrice.length) usedPrice = usedPrice[0].firstChild.nodeValue;
  175.             
  176.             var subject = rdfService.GetResource(url);
  177.             
  178.             var predicate = rdfService.GetResource("http://home.netscape.com/NC-rdf#Name");
  179.             var name = rdfService.GetLiteral(title);                
  180.             aDatasource.Assert(subject, predicate, name, true);
  181.     
  182.             var predicate = rdfService.GetResource("http://home.netscape.com/NC-rdf#URL");
  183.             var name = rdfService.GetLiteral(url);
  184.             aDatasource.Assert(subject, predicate, name, true);
  185.             
  186.             if (thumbnailUrl && thumbnailUrl.length) {
  187.               var predicate = rdfService.GetResource("http://home.netscape.com/NC-rdf#favicon");
  188.               var name= rdfService.GetLiteral(thumbnailUrl);
  189.               aDatasource.Assert(subject, predicate, name, true);
  190.             }
  191.             
  192.             if (listPrice) {
  193.                 var predicate = rdfService.GetResource("http://home.netscape.com/NC-rdf#Price");
  194.                 var name= rdfService.GetLiteral(listPrice);
  195.                 aDatasource.Assert(subject, predicate, name, true);
  196.             }
  197.             
  198.             typeContainer.AppendElement(subject);
  199.  
  200.         }
  201.         
  202.         rootContainer.AppendElement(typeNode);
  203.     }
  204.         
  205.       } catch(ex) {
  206.         //debug('amazon Exception occurred while reading XML (i=' + i + '; start=' + start + ';end=' + end + '): ' + exception);
  207.         debug('>>>> amazon error ' + ex + '\n');
  208.       }
  209.       
  210.       return aDatasource;
  211.     }
  212.  
  213.  
  214. amazonSearchService.prototype.flags = nsIClassInfo.SINGLETON;
  215. amazonSearchService.prototype.classDescription = "Amazon Search Service";
  216. amazonSearchService.prototype.getInterfaces = function (count) {
  217.     var interfaceList = [flockISearchService, nsIClassInfo];
  218.     count.value = interfaceList.length;
  219.     return interfaceList;
  220. }
  221. amazonSearchService.prototype.getHelperForLanguage = function (count) {return null;}
  222.  
  223. // the nsISupports implementation
  224. amazonSearchService.prototype.QueryInterface =
  225. function (iid) {
  226.     if (!iid.equals(flockISearchService) && 
  227.         !iid.equals(nsIClassInfo) &&
  228.         !iid.equals(nsISupports))
  229.         throw Components.results.NS_ERROR_NO_INTERFACE;
  230.     if (iid.equals(nsIRDFDataSource) && !this.dataSourceSetup) {
  231.     }
  232.     return this;
  233. }
  234.  
  235. // Module implementation
  236. var FlockSearchModule = new Object();
  237.  
  238. FlockSearchModule.registerSelf =
  239. function (compMgr, fileSpec, location, type)
  240. {
  241.     compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  242.  
  243.     compMgr.registerFactoryLocation(AMAZON_SEARCH_CID, 
  244.                                     "Amazon Search JS Component",
  245.                                     AMAZON_SEARCH_CONTRACTID, 
  246.                                     fileSpec, 
  247.                                     location,
  248.                                     type);
  249.     //necessary category registration
  250.     var catmgr = Components.classes["@mozilla.org/categorymanager;1"]
  251.         .getService (Components.interfaces.nsICategoryManager);
  252.     catmgr.addCategoryEntry('flockISearchService', 'amazon', AMAZON_SEARCH_CONTRACTID, true, true);
  253. }
  254.  
  255. FlockSearchModule.getClassObject =
  256. function (compMgr, cid, iid) {
  257.     if (!cid.equals(AMAZON_SEARCH_CID))
  258.         throw Components.results.NS_ERROR_NO_INTERFACE;
  259.     
  260.     if (!iid.equals(Components.interfaces.nsIFactory))
  261.         throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  262.     
  263.     return SeachServiceFactory;
  264. }
  265.  
  266. FlockSearchModule.canUnload =
  267. function(compMgr)
  268. {
  269.     return true;
  270. }
  271.     
  272. /* factory object */
  273. var SeachServiceFactory = new Object();
  274.  
  275. SeachServiceFactory.createInstance =
  276. function (outer, iid) {
  277.     if (outer != null)
  278.         throw Components.results.NS_ERROR_NO_AGGREGATION;
  279.     return (new amazonSearchService()).QueryInterface(iid);
  280. }
  281.  
  282. /* entrypoint */
  283. function NSGetModule(compMgr, fileSpec) {
  284.     return FlockSearchModule;
  285. }
  286.